"""
-*- coding: utf-8 -*-
@Author  : Link
@Time    : 2022/2/14 14:55
@Software: PyCharm
@File    : __init__.py.py
@Remark  : 
"""
import ctypes
import os


class CppStdfLink:
    STDF_RETURN = {
        0: "STDF_OPERATE_OK",
        -1: "READ_ERROR",
        -2: "FORMATE_ERROR",
        -3: "STDF_CPU_TYPE_NOT_SUPPORT",
        -4: "STDF_VERSION_NOT_SUPPORT",  # 这个只是我不懂的类型, 不是说不需要的类型
        -5: "WRITE_ERROR",  # 这个只是我不懂的类型, 不是说不需要的类型
    }

    def __init__(self):
        cur_path = os.path.dirname(__file__)
        dll_path = os.path.join(cur_path, "")
        std_dll = ctypes.cdll.LoadLibrary(os.path.join(dll_path, "./csv_to_stdf.dll"))

        "宏杰科"
        self._aswc_csv_to_stdf = std_dll.ExecAswcCsvToStdf
        self._aswc_csv_to_stdf.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p]
        self._aswc_csv_to_stdf.restype = ctypes.c_int

        "三安"
        self._sanan_csv_to_stdf = std_dll.ExecSananCsvToStdf
        self._sanan_csv_to_stdf.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_char_p]
        self._sanan_csv_to_stdf.restype = ctypes.c_int

    @staticmethod
    def string_to_char(_string: str) -> ctypes.Array:
        return ctypes.create_string_buffer(bytes(_string, encoding='utf8'))

    @staticmethod
    def string_to_wchar(_string: str):
        return ctypes.create_unicode_buffer(_string)

    @staticmethod
    def char_to_string(c_char: ctypes.c_char_p) -> str:
        temp_bytes = ctypes.string_at(c_char)
        return temp_bytes.decode("utf-8")

    def exec_aswc_csv_to_stdf(self, csv_file: str, save_file: str):
        return self._aswc_csv_to_stdf(self.string_to_wchar(csv_file), self.string_to_wchar(save_file))

    def exec_sanan_csv_to_stdf(self, csv_file: str, save_file: str, wafer_id: str):
        return self._sanan_csv_to_stdf(self.string_to_wchar(csv_file), self.string_to_wchar(save_file),
                                       self.string_to_char(wafer_id))


if __name__ == '__main__':
    stdf = CppStdfLink()
    sanan_file = r"E:\CP_SANAN\A08697W04_20220515150236.csv"
    file_nam, suffix = os.path.splitext(sanan_file)
    finally_save_path = os.path.join(r"E:\CP_SANAN\验证数据", file_nam + '.stdf')
    save_path = os.path.join(r"E:\CP_SANAN\验证数据", file_nam + '.std_temp')
    resp = stdf.exec_sanan_csv_to_stdf(sanan_file, save_path, "A08697#04")
    if resp != 0:
        os.remove(save_path)
    else:
        os.rename(save_path, finally_save_path)